﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;

namespace Wechat.Util.WechatUtil
{
    public class WechatMsgUtil
    {
        #region 解析xml

        /// <summary>
        /// 解析微信XML
        /// </summary>
        /// <param name="xmlDoc"></param>
        /// <returns></returns>
        public static WechatXmlMsg GetExmlMsg(XmlDocument xmlDoc)
        {
            WechatXmlMsg exmlMsg = new WechatXmlMsg()
            {
                FromUserName = GetFromXML(xmlDoc, "FromUserName"),
                ToUserName = GetFromXML(xmlDoc, "ToUserName"),
                CreateTime = GetFromXML(xmlDoc, "CreateTime").ToLower(),
                MsgType = GetFromXML(xmlDoc, "MsgType").ToLower()

            };
            switch (exmlMsg.MsgType)
            {
                case "text":
                    exmlMsg.Content = GetFromXML(xmlDoc, "Content");
                    break;
                case "event":
                    exmlMsg.EventName = GetFromXML(xmlDoc, "Event").ToLower();
                    if (exmlMsg.EventName == "click")
                    {
                        exmlMsg.EventKey = GetFromXML(xmlDoc, "EventKey");
                    }
                    break;
                case "image":
                    exmlMsg.PicUrl = GetFromXML(xmlDoc, "PicUrl");
                    break;
                default:
                    break;
            }
            return exmlMsg;
        }
        #endregion

        #region GetFormXml
        private static string GetFromXML(XmlDocument xmlDoc, string name)
        {
            XmlNode node = xmlDoc.SelectSingleNode("xml/" + name);
            if (node != null && node.ChildNodes.Count > 0)
            {
                return node.ChildNodes[0].Value;
            }
            return "";
        }
        #endregion

        #region 编辑消息

        /// <summary>
        /// 文字消息
        /// </summary>
        /// <param name="xmlMsg"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string CreateTextMsg(WechatXmlMsg xmlMsg, string content)
        {
            string strTpl = string.Format(@"<xml>
                <ToUserName><![CDATA[{0}]]></ToUserName>
                <FromUserName><![CDATA[{1}]]></FromUserName>
                <CreateTime>{2}</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[{3}]]></Content>
                </xml>", xmlMsg.FromUserName, xmlMsg.ToUserName,
                       ConvertDateTimeInt(DateTime.Now), content);

            return strTpl;
        }

        /// <summary>
        /// 图文消息
        /// </summary>
        /// <param name="xmlMsg"></param>
        /// <param name="imgUrl"></param>
        /// <returns></returns>
        public static string CreateImageMsg(WechatXmlMsg xmlMsg, string imgUrl)
        {
            string strTpl = string.Format(@"<xml>
                <ToUserName><![CDATA[{0}]]></ToUserName>
                <FromUserName><![CDATA[{1}]]></FromUserName>
                <CreateTime>{2}</CreateTime>
                <MsgType><![CDATA[news]]></MsgType>
                <ArticleCount><![CDATA[{3}]]></ArticleCount>
                <Articles>", xmlMsg.FromUserName, xmlMsg.ToUserName,
                       ConvertDateTimeInt(DateTime.Now), 1);
            strTpl += string.Format(@"
                <item>
                <Title><![CDATA[{0}]]></Title> 
                <Description><![CDATA[{1}]]></Description>
                <PicUrl><![CDATA[{2}]]></PicUrl>
                <Url><![CDATA[{3}]]></Url>
                </item>", "图片", "您发送的照片", imgUrl, imgUrl);
            strTpl += string.Format(@"
                </Articles>
                </xml> ");
            return strTpl;
        }
        #endregion

        #region 将datetime.now 转换为 int类型的秒
        /// <summary>
        /// datetime转换为unixtime
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        private static int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }


        #endregion

        #region 向指定url POST数据，并获得返回结果

        /// <summary>
        /// 向指定url POST数据，并获得返回结果
        /// </summary>
        /// <param name="posturl"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string PostData(string posturl, string postData)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                //Response.Write(content);
                return content;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        #endregion

        #region 向指定url Get，并获得返回结果

        /// <summary>
        /// 向指定url Get，并获得返回结果
        /// </summary>
        /// <param name="posturl"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string GetData(string posturl, string postData)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                //Response.Write(content);
                return content;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        #endregion

        #region 向指定url发送数据，获取返回值

        /// <summary>
        /// 向指定url发送数据，获取返回值
        /// </summary>
        /// <param name="posturl"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string GetPage(string posturl, string postData)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                //System.Web.HttpContext.Current.Response.Write(content);
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }
        #endregion

    }
}
